//
//  MyTeamViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/21.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "MyTeamViewController.h"
#import "MyTeamView.h"
#import "MyTeamTableViewCell.h"

#import <Masonry.h>
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>

#import "MyTeamModePack.h"


@interface MyTeamViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)MyTeamView *mv;
@property(nonatomic,strong)UITableView *tableView;


//模型数组
@property(nonatomic,strong)NSMutableArray *recordArray;

// 上拉下拉刷新相关属性
@property(nonatomic,assign) NSInteger curPageNum;
@property(nonatomic,strong) NSString *ifHasMore; // 是否有更多数据 0:无 1:有
@property(nonatomic,assign) ETRefreshType refreshType;
@property(nonatomic,assign) BOOL isLoading;

@end

@implementation MyTeamViewController


#pragma mark 上拉刷新&下拉刷新
- (void)createHeaderView{
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 设置文字
    [headerView setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [headerView setTitle:@"释放刷新" forState:MJRefreshStatePulling];
    [headerView setTitle:@"加载中 ..." forState:MJRefreshStateRefreshing];
    // 设置字体
    headerView.stateLabel.font = [UIFont systemFontOfSize:15];
    headerView.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    // 设置颜色
    headerView.stateLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    headerView.lastUpdatedTimeLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    self.tableView.mj_header = headerView;
}

- (void)createFooterView
{
    MJRefreshBackNormalFooter *footerView = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // 设置文字
    [footerView setTitle:@"上拉刷新" forState:MJRefreshStateIdle];
    [footerView setTitle:@"正在加载更多数据" forState:MJRefreshStateRefreshing];
    [footerView setTitle:@"-已经到底了-" forState:MJRefreshStateNoMoreData];
    // 设置字体
    footerView.stateLabel.font = [UIFont systemFontOfSize:13];
    // 设置颜色
    footerView.stateLabel.textColor = [UIColor colorWithRed:153 / 255.0 green:153 / 255.0 blue:153 / 255.0 alpha:1];
    self.tableView.mj_footer = footerView;
}

- (void)loadNewData{
    if (self.isLoading) {
        return;
    }
    self.curPageNum = 1;
    self.refreshType = ETRefreshDown;
    
     [self getNetMyTeamInfo];
    
}

- (void)loadMoreData{
    if (self.isLoading) {
        return;
    }
    self.refreshType = ETRefreshUp;
    self.curPageNum++;
    if ([self.ifHasMore isEqualToString:@"0"]) {
        /*
         [self showSuccessResultTips:@"无更多数据" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF];
         */
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
     [self getNetMyTeamInfo];
}

-(NSMutableArray *)recordArray
{
    if (_recordArray == nil) {
        _recordArray = [NSMutableArray array];
    }
    return _recordArray;
}

-(void)loadView
{
    [super loadView];
    self.mv = [[MyTeamView alloc] initWithFrame:self.view.bounds];
    self.view = self.mv;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的团队";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    //创建tableView
    [self createTableView];
    
    // 上拉下拉刷新相关设置
    self.curPageNum = 1;
    self.ifHasMore = @"0";
    [self createHeaderView];
    [self createFooterView];
    
    //获取团队列表
    [self getNetMyTeamInfo];
    
    
        
}
-(void)getNetMyTeamInfo
{
    MyTeamRequest *request = [[MyTeamRequest alloc] init];
    request.action = @"down";
    request.pageNum = [NSString stringWithFormat:@"%ld",(long)self.curPageNum];
    request.pageSize = PAGESIZE;
    self.isLoading = YES;
    NSDictionary *dic = [request mj_JSONObject];
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/team/selectTeamListD0200"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:dic HttpBody:nil SuccessHandler:^(id responseObject) {
        
        self.isLoading = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
            [self dealMyteamInfoWithObject:responseObject];
            });
        }else
        {
            [self.tableView removeFromSuperview];
        }
        
    } FailedHandler:^(NSError *error) {
        
        self.isLoading = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView removeFromSuperview];
        
    }];
}
-(void)dealMyteamInfoWithObject:(id)responseObject
{
    MyTeamResponse *myTeamresponse = [MyTeamResponse mj_objectWithKeyValues:responseObject];
    [AppTools shareInstance].userInfo.recomendNum = myTeamresponse.response.totalCount;
    if (myTeamresponse.response.list.count == 0) {
        [self.tableView removeFromSuperview];
    }
    
    if (self.refreshType == ETRefreshUp) {
        for (MyTeamRecord *recored in myTeamresponse.response.list) {
            [self.recordArray addObject:recored];
        }
    }else
    {
        [self.recordArray removeAllObjects];
        for (MyTeamRecord *recored in myTeamresponse.response.list) {
            [self.recordArray addObject:recored];
        }
        
    }
    
    
    if (myTeamresponse.response.list.count < 10) {
        self.ifHasMore = @"0";
    }else
    {
        self.ifHasMore = @"1";
    }
    
    
    self.mv.nameLab.text = [NSString stringWithFormat:@"姓名(%@人)",myTeamresponse.response.totalCount];
    [self.tableView reloadData];
    
    self.isLoading = NO;
    
    
}

-(void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.recordArray.count * 44) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerClass:[MyTeamTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.mv.midView.mas_bottom);
        make.bottom.equalTo(self.view);
    }];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.recordArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    [cell.nameLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mv.nameLab);
    }];
    [cell.dateLab mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mv.registeDate);
    }];
    [cell.imv mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mv.levelLab);
    }];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    /*
    cell.nameLab.text = self.nameArray[indexPath.row];
    cell.dateLab.text = self.registerDateArray[indexPath.row];
    cell.levelLab.text = self.levelArray[indexPath.row];
     */
    MyTeamRecord *record = self.recordArray[indexPath.row];
    cell.nameLab.text = record.userName;
    cell.dateLab.text = record.registerTime;
    [cell.imv sd_setImageWithURL:[NSURL URLWithString:record.image]];
    //最后一个cell不显示分割线
    if (indexPath.row == self.recordArray.count - 1) {
        cell.lineView.hidden = YES;
    }

    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0.01)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


@end
